#include "upload_file.h"

#include "client_define.h"

upload_file::upload_file(QObject *parent)
        : QObject{parent} {

}


void upload_file::Upload(QString path) {
    this->file_socket = new QTcpSocket(this);
    file_socket->abort();
    file_socket->connectToHost(FILE_SERVER_HOST, FILE_SERVER_PORT);

    connect(file_socket, &QTcpSocket::connected, this, []() {
        qDebug() << "fileSocket->connected()";
    });

    //通知主线程断开连接
    connect(file_socket, &QTcpSocket::disconnected, this, [=]() {
        //断开连接，释放资源
        file_socket->close();
        file_socket->deleteLater();
        // emit socket_disconnect();
    });
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [=]() {
        //关闭定时器
        timer->stop();
        //发送文件数据
        sendfileData();
    });

    file.setFileName(path);
    //获取文件信息
    QFileInfo info(path);
    total_bytes = info.size();//获取文件大小
    filename = info.fileName();//获取文件名
    bytes_send = 0;
    qDebug() << filename << " " << total_bytes;
    //只读方式打开文件
    bool isOk = file.open(QIODevice::ReadOnly);
    if (true == isOk) {
        qDebug() << filename;
        //创建文件头信息
        QString head = QString("%1##%2##%3").arg(filename).arg(total_bytes).arg(username);
        //发送头部信息
        qint64 len = file_socket->write(head.toUtf8());
        if (len > 0) {
            //防止tcp黏包问题,延时20ms
            timer->start(20);
        } else {
            //发送失败
            file.close();
        }

    } else {
        // emit finish();
        return;
    }

}

void upload_file::sendfileData() {
    qint64 len = 0;
    do {
        char buf[4 * 1024] = {0}; // 每次发送的大小
        len = file.read(buf, sizeof(buf));  // 记录每行数据
        bytes_send += len;
        file_socket->write(buf, len); // 发送数据
    } while (len > 0);

    qDebug() << bytes_send << "  " << total_bytes << "  " << filename;

    if (bytes_send == total_bytes) {
        file.close();
        filename.clear();
        total_bytes = 0;
        emit finish();
    }
}

void upload_file::setUsername(const QString &newUsername) {
    username = newUsername;
}
